#include "apue.h"
#include <pthread.h>

static int has_ready= 0;
static pthread_mutex_t ready_lock= PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t ready_cond= PTHREAD_COND_INITIALIZER;

void *thr_fn(void *arg) {
    pthread_t pt; 
    pt= pthread_self();

    pthread_mutex_lock(&ready_lock);
    while (has_ready == 0)
        pthread_cond_wait(&ready_cond, &ready_lock);


    printf("thread %lu running\n", pt);
    pthread_mutex_unlock(&ready_lock);
    pthread_exit(0);
}

int main() {
    pthread_t p1, p2, p3, p4;
    pthread_create(&p1, NULL, thr_fn, NULL);
    pthread_create(&p2, NULL, thr_fn, NULL);
    pthread_create(&p3, NULL, thr_fn, NULL);
    pthread_create(&p4, NULL, thr_fn, NULL);

    pthread_mutex_lock(&ready_lock);
    has_ready= 1;
    pthread_mutex_unlock(&ready_lock);
    pthread_cond_broadcast(&ready_cond);
    printf("Main thread running\n");
    sleep(2);
}


